//
//  GetAddressViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/21.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "GetAddressViewController.h"
#import "HeaderFileForEasyToTesco.h"
#import "AFNetworking.h"

#import "ReadLoginData.h"
//收货地址
#import "OrderDetailTableViewCell.h"
//管理收货地址
#import "ManagerViewController.h"

#import "ConfirmViewController.h"

@interface GetAddressViewController ()<UITableViewDataSource, UITableViewDelegate>{
    
    NSIndexPath *index;
    
}


@property (nonatomic, strong)UITableView *GetAddresstableview;
@property (nonatomic, strong)NSMutableArray *wholeAddArray;
@property (nonatomic, assign)NSInteger i;
@end

@implementation GetAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self addgetaddressinitsomething];
    
    [self addGetAddressTopUI];
    
    [self addgetaddresstableviewUI];

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addgetaddressinitsomething];
}

- (void)addgetaddressinitsomething {
    self.wholeAddArray  = [@[]mutableCopy];
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count != 0) {
        [self addgetaddressdatasources:[dic[@"data"] objectForKey:@"username"]];
    }
    
}

- (void)addGetAddressTopUI {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"选择收货地址";
    
    UIButton *editBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    editBtn.frame = CGRectMake(WEITH-CGRectGetHeight(self.secondView.frame)-5, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [editBtn addTarget:self action:@selector(editBtn) forControlEvents:UIControlEventTouchUpInside];
    [editBtn setTitle:@"添加" forState:UIControlStateNormal];
    [self.secondView addSubview:editBtn];

}

- (void)editBtn {
    ManagerViewController *managerVC = [[ManagerViewController alloc] init];
    [self presentViewController:managerVC animated:YES completion:nil];
}

- (void)gobackClick {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addgetaddresstableviewUI{
    self.GetAddresstableview = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.secondView.frame), WEITH, HIGHT - CGRectGetMaxY(self.secondView.frame)) style:UITableViewStylePlain];
    self.GetAddresstableview.dataSource = self;
    self.GetAddresstableview.delegate = self;
    self.GetAddresstableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.GetAddresstableview];
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.wholeAddArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"OrderDetailTableViewCellget";
        OrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderDetailTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
          
        }
    
    cell.orderDetailName.text = self.wholeAddArray[indexPath.row][@"name"];
    cell.orderDetailPhoneNum.text= self.wholeAddArray[indexPath.row][@"phone"];
    cell.orderDetailAddress.text=[NSString stringWithFormat:@"%@ %@ %@ %@ ",  self.wholeAddArray[indexPath.row][@"province"], self.wholeAddArray[indexPath.row][@"city"],self.wholeAddArray[indexPath.row][@"county"],self.wholeAddArray[indexPath.row][@"address"]];

//
    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
#pragma mark -- 点击cell后返回到上一级页面
    ConfirmViewController *vc = [[ConfirmViewController alloc] init];
    vc.confirmDic = self.wholeAddArray[indexPath.row];
    vc.arrayNum = indexPath.row;
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:ShopCarGetAddressNotification object:nil userInfo:self.wholeAddArray[indexPath.row]];
        
    }];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

//Cell可编辑
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
//定义编辑样式
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete;
//}

//- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return @"删除";
//}
//
////进入编辑模式，按下出现的编辑按钮后
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//    
//            [self.wholeAddArray removeObjectAtIndex:indexPath.row];
//        [self.GetAddresstableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//    }
//}

//获取当前用户的收货地址
- (void)addgetaddressdatasources:(NSString *)nameStr {
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = nameStr;
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username]};
    
    [mgr POST:@"http://www.ylgw8.com/AppUser/Getdz" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
       self.wholeAddArray  = [self toArrayOrNSDictionary:responseObject][@"data"];
//        NSLog(@"~~!!~%@", self.wholeAddArray);
        

        [self.GetAddresstableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}


@end
